<?php
class view {
	
	public $modelname;
	public $viewname;
	
	public $structure;
	
	function __construct($modelname, $viewname) {
		$this->modelname = $modelname;
		$this->viewname = $viewname;
		$xml_model = new xml("models/$modelname.xml");
		$xml_specific = new xml("views/$modelname/$viewname.xml");
		$xml = self::merge($xml_model->getContents(), $xml_specific->getContents());
		$this->structure = $xml;
		foreach($this->structure as &$field) {
			$classname = "fieldtype_".$field['type'];
			$field = new $classname($field);
			$field->view = $viewname;
		}
	}
		
	function load($pos = null) {
		request::set("view", $this);
		$req = new request(array("module" => "view", "action" => $this->viewname));
		module::loadToPosition($req, $pos ? $pos : $this->modelname."_".$this->viewname);
	}
	
	public function loadModel() {
		$classname = $this->modelname;
		return new $classname();
	}
	
	public function getFieldNames() {
		$ret = array();
		foreach($this->structure as $field => $arg) {
			$ret[] = $field;
		}
		return $ret;
	}
	
	public function getFieldOrder($fieldname) {
		return $this->structure[$fieldname]->order;
	}
	
	public function getOrderedFieldList() {
		$data = array();
		$order = array();
		foreach($this->getFieldNames() as $fieldname) {
			$data[] = $this->structure[$fieldname];
			$order[] = $this->getFieldOrder($fieldname);
		}
		array_multisort($order, $data);
		return $data;
	}
	
	static function merge(&$a1, &$a2, $level = 0) {
    $newArray = array();
    foreach ($a1 as $key => $v) { 
        if (!isset($a2[$key])) {
        	if ($level != 0) {
            	$newArray[$key] = $v;
			}
            continue;
        }

        if (is_array($v)) {
            if (!is_array($a2[$key])) {
                $newArray[$key] = $a2[$key];
                continue;
            }
            $newArray[$key] = view::merge($a1[$key], $a2[$key], $level + 1);
            continue;
        }
        $newArray[$key] = $a2[$key];
    }
	// values in a2 not in a1?
	foreach($a2 as $key => $v) {
		if (!isset($a1[$key])) {
			$newArray[$key] = $a2[$key];
		}
	}
    return $newArray;
}
	
}
?>